package com.antdesignbackend.backend.task;

import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.entity.entityVo.AppointmentVo;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时器计划任务等
 */

@Component
public class ScheduledTask {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private final IAppointmentService appointmentService;
    private final UserService userService;
    private final IRoomService roomService;
    private final IShopService shopService;
    private final ChargingFlowService chargingFlowService;
    private final UsereventService usereventService;
    private final EventService eventService;
    private final ReturnformService returnformService;
    private final SubscriptionService subscriptionService;

    @Autowired
    public ScheduledTask(IAppointmentService appointmentService,UserService userService,IShopService shopService,
                         ChargingFlowService chargingFlowService,IRoomService roomService,UsereventService usereventService,
                         EventService eventService,ReturnformService returnformService,SubscriptionService subscriptionService) {
        this.appointmentService = appointmentService;
        this.userService = userService;
        this.shopService = shopService;
        this.chargingFlowService = chargingFlowService;
        this.roomService = roomService;
        this.usereventService = usereventService;
        this.eventService = eventService;
        this.returnformService = returnformService;
        this.subscriptionService = subscriptionService;
    }

    /***
     * 对还未分成的流水
     * 进行分成
     * XXX分钟执行一次
     * @return
     */
    //Scheduled(cron = "0 0/1 * * * ?")
    public void isStreamFlag() {
        System.out.println("*******************开始isStreamFlag******************");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Appointment> datalist=new ArrayList<>();
        QueryWrapper<Appointment> wrapper =new QueryWrapper<Appointment>();
        wrapper.lt("startTime",sdf.format(new Date()));
        wrapper.eq("state",1);
        wrapper.ne("streamFlag",1);
        wrapper.ne("isCancel",1);
        datalist= appointmentService.getBaseMapper().selectList(wrapper);
        if(datalist.size()>0){
            for(Appointment app:datalist){
                //开始流水分成
                String attributionOrder=app.getOrderNumber();
                Double amount=app.getAmount();
                if(amount>0){
                    if(app.getShopId()!=null && app.getRoomId()!=null){
                        Room room=new Room();
                        room= roomService.getById(app.getRoomId());
                        Users shops = new Users();
                        shops= userService.getById(app.getUserId());
                        Users shop = userService.getById(shops.getParentID());
                        Integer type=shop.getUserType();
                        if(type!=null && !type.equals("")){
                            switch (type){
                                case 3:
                                    //服务商分成
                                    Double balanceA=shop.getAmount()+amount*0.05;
                                    shop.setAmount(balanceA);
                                    userService.updateById(shop);
                                    //计入明细
                                    AddCharging(shop.getUserName(),shop.getUserID(),amount*0.05,room.getName()+"流水服务商分成",attributionOrder);
                                    //区域合伙人分成
                                    Integer shopBId=shop.getParentID();
                                    Users shopB = userService.getById(shopBId);
                                    if(shopB.getUserType()!=1){
                                        Double balanceB=shopB.getAmount()+amount*0.02;
                                        shopB.setAmount(balanceB);
                                        userService.updateById(shopB);
                                        //计入明细
                                        AddCharging(shopB.getUserName(),shopB.getUserID(),amount*0.02,room.getName()+"流水合伙人分成",attributionOrder);
                                    }
                                    Shop sh=new Shop();
                                    sh=shopService.getById(app.getShopId());
                                    Users users = new Users();
                                    users= userService.getById(sh.getUserId());
                                    Double balanceU=users.getAmount()+amount*0.90;
                                    users.setAmount(balanceU);
                                    userService.updateById(users);
                                    AddCharging(users.getUserName(),users.getUserID(),amount*0.90,room.getName()+"流水商铺分成",attributionOrder);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
                Appointment appointment=new Appointment();
                appointment= appointmentService.getById(app.getId());
                appointment.setStreamFlag(1);
                appointmentService.updateById(appointment);
            }
        }
        System.out.println("*******************结束isStreamFlag******************");
    }
    /***
     * 对还未付款的订单
     * 进行过期处理
     * 2分钟执行一次
     * @return
     */
    //Scheduled(cron = "0 0/1 * * * ?")
    public void isUpTime() {
        System.out.println("*******************开始isUpTime******************");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beginDate = CalendarDate.addDate(new Date(), "min", -2);
        List<Appointment> datalist=new ArrayList<>();
        QueryWrapper<Appointment> wrapper =new QueryWrapper<Appointment>();
        wrapper.lt("startTime",beginDate);
        wrapper.eq("state",0);
        datalist= appointmentService.getBaseMapper().selectList(wrapper);
        for (Appointment app:datalist){
            app.setState(-1);
            appointmentService.updateById(app);
        }
        System.out.println("*******************结束isUpTime******************");
    }
    /***
     * 对办卡用户
     * 进行返还
     * 每年的一月一号轮询
     * @return
     */
    //@Scheduled(cron = "0 0 0 1 1 ?")
    public void yearReturn() {
        System.out.println("*******************开始yearReturn******************");
        QueryWrapper<Userevent> wrapper =new QueryWrapper<Userevent>();
        wrapper.gt("returnTimes",0);
        wrapper.eq("isYear",1);
        List<Userevent> datalist= usereventService.getBaseMapper().selectList(wrapper);
        for (Userevent userevent:datalist){
            //查询参加活动
            QueryWrapper<Event> eventWrapper =new QueryWrapper<Event>();
            eventWrapper.eq("eventId",userevent.getEventId());
            Event event=eventService.getOne(eventWrapper);
            //存入用户返还表
            Returnform returnform=new Returnform();
            returnform.setUserId(userevent.getUserId());
            returnform.setEventId(userevent.getEventId());
            returnform.setReturnAmount(event.getYearReturn());
            returnform.setReturnTime(new Date());
            returnform.setOperator("定时返还");
            returnformService.save(returnform);
            //对用户存入一次返还金额
            Users users=userService.getById(userevent.getUserId());
            users.setFrozenAmount(users.getFrozenAmount()+event.getYearReturn());
            userService.updateById(users);
            //减少返还次数
            userevent.setReturnTimes(userevent.getReturnTimes()-1);
            usereventService.updateById(userevent);
        }
        System.out.println("*******************结束yearReturn******************");
    }
    /***
     * 对包月用户
     * 进行取消
     * 每天的0点
     * @return
     */
    //@Scheduled(cron = "0 0 0 * * ?")
    public void monthlyCancel() {
        System.out.println("*******************开始monthlyCancel******************");
        QueryWrapper<Users> wrapper =new QueryWrapper<Users>();
        wrapper.eq("isMonthly",1);
        List<Users> datalist= userService.getBaseMapper().selectList(wrapper);
        for(Users users:datalist){
            QueryWrapper<Subscription> subWrapper =new QueryWrapper<Subscription>();
            subWrapper.eq("userId",users.getUserID());
            subWrapper.eq("state",1);
            subWrapper.gt("endTime",new Date());
            List<Subscription> sublist= subscriptionService.getBaseMapper().selectList(subWrapper);
            if(sublist.size()==0){
                users.setIsMonthly(0);
                userService.updateById(users);
            }
        }
        System.out.println("*******************结束monthlyCancel******************");
    }
    /***
     * 计入明细
     */
    public void AddCharging(String name,Integer userId,Double money,String remark,String attributionOrder){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = formatter.format(new Date());
        ChargingFlow chargingFlow = new ChargingFlow();
        chargingFlow.setName(name);
        chargingFlow.setUserId(userId);
        chargingFlow.setMoney(money);
        chargingFlow.setRemark(remark);
        chargingFlow.setCreateTime(date);
        chargingFlow.setAttributionOrder(attributionOrder);
        chargingFlowService.save(chargingFlow);
    }

}
